<template>
    <div class="warpper-box">
        <form-create 
        v-model="params.fApi" 
        :rule="params.rule" 
        :option="params.option" 
        @btn-search-click="loadTable(true)"
        @btn-reset-click="reset"/>
        <a-button type="danger" v-action:operateAddBtn @click="add(true)" icon="plus">新增</a-button>
        <a-button type="primary" @click="checkUserShare()" icon="bars">共享用户列表</a-button>
         <a-table :columns="table.columns" :pagination="table.pagination" @change="handleTableChange" rowKey="id" :data-source="table.loadData">
          <span slot="status" slot-scope="text, record">
            <a-popconfirm
                :title="record.status === 1 ? '禁用状态，账号不能使用？确认禁用！':'确认启用！'"
                ok-text="确认"
                cancel-text="取消"
                @confirm="handelUserStatusChange(record)" >
                 <a-switch checked-children="启用" un-checked-children="禁用" 
                :checked="record.status === 1 ? true : false"
                default-checked />
            </a-popconfirm>
          </span>
          <span slot="share" slot-scope="text, record">
            <a-switch checked-children="共享" @change="handelUserShare(record)"
            :checked="record.isShare === 1 ? true : false"
            default-checked />
          </span>
          <span slot="action" slot-scope="text, record">
            <a @click="add(record)" v-action:operateEditBtn>编辑</a>
            <a-divider type="vertical" v-action:operateEditBtn/>
            <a-popconfirm
              title="删除将解绑该管理员与对应企业关联关系，是否删除?"
              ok-text="删除"
              cancel-text="取消"
              @confirm="del(record)">
                <a href="#" v-action:operateDelBtn>删除</a>
              </a-popconfirm>
              <a-divider type="vertical" v-action:operateDelBtn/>
              <a-popconfirm
              title="是否密码重置 Aa123456?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="resetPwd(record)">
                <a href="#" v-action:operateSetBtn>重置密码</a>
              </a-popconfirm>

            </span>
        </a-table>
         <a-modal :title="form.title" :width="640" :visible="form.visible" @ok="handleSubmit" @cancel="form.visible=false">
            <form-create v-model="form.fApi" :rule="form.rule" :option="form.option"/>
        </a-modal>
        <!-- 共享用户列表 -->
        <a-modal title="共享用户" :width="480" :visible="shareTable.visible" @cancel="shareTable.visible=false">
          <a-table :columns="shareTable.columns" :pagination="false" @change="handleTableChange" rowKey="id" :data-source="shareTable.loadData">
          </a-table>
        </a-modal>
    </div>
</template>

<script>
  import Vue from 'vue'
 import store from '@/store'
 import md5 from 'md5'
import { 
  sysOperateUserList, 
  sysAddOperateUser,
  sysEditOperateUser,
  sysOperateDelUser,
  sysOperateEnableUser,
  sysResetPasswordOperateUser,
  postUserShare,
  postUserDeleteShare,
  getUserShareList
} from '@/api/manage/user'
import {
  PARAMS_ADMIN,
  FORM_ADMIN,
  FORM_SET_PWD_ADMIN,
  ADMIN_COLUMNS,
  OPTION_BLOCK,
  OPTION_INLINE,
  ADMIN_SHARE
} from './modules/form'
import { mapGetters } from 'vuex'
export default {
  name: 'operate',
  data () {
    return {
        params:{
          fApi:{},
          rule:PARAMS_ADMIN,
          option:OPTION_INLINE
        },
        form:{
           visible:false,
           id:'',
           title:'',
            fApi:{},
            rule:[],
            option:OPTION_BLOCK
        },
        pagination: {current:1,pageSize:10},
        table:{
          columns:ADMIN_COLUMNS,
          loadData:[],
          pagination:{
            current:1,
            pageSize: 10,
             total:0,
            showSizeChanger: true,
					showQuickJumper: true,
            pageSizeOptions: ["10", "20", "50", "100"],
            showTotal: total => `共有 ${total} 条数据`,
          }
        },
        shareTable:{
          visible: false,
          columns:ADMIN_SHARE,
          loadData:[],
          pagination:{
            current:1,
            pageSize: 10,
            total:0,
            showSizeChanger: true,
					showQuickJumper: true,
            pageSizeOptions: ["10", "20", "50", "100"],
            showTotal: total => `共有 ${total} 条数据`,
          }
        },
        userRoleOptions:[]
    }
  },
  mounted () {
    this.loadTable(true);
    this.getUserRoleData();
    let _this = this;
    document.onkeydown = function(e) {
      e = e || window.event;
      if (e.keyCode == 13) {
        _this.loadTable(true);
      }
    };
  },
   computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    async getUserRoleData(){
      this.userRoleOptions = await store.dispatch('getSysGetBaseUserRole',this.userInfo.relationId);
    },
    async getShareList() {
      const {code,data} = await getUserShareList();
      if (code == "1") {
        this.shareTable.loadData = data;
      }
    },
    async loadTable(flag){
       let params = {};
      if(JSON.stringify(this.params.fApi) !== "{}"){
         params.keyword = this.params.fApi.getValue('keyword');
      }
      if(flag){
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.relationId = this.userInfo.relationId;//园区id,企业id，为-1表示管理端
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const {code,data} = await sysOperateUserList(params);
      if(code ==='1'){
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
     handleTableChange(pagination){
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    async handelUserStatusChange(el){
      const status = el.status === 1 ? 2:1;
      const {code} = await sysOperateEnableUser(status,el.id);
      if(code === '1'){
        this.$message.success('操作成功');
        this.loadTable(false);
      }
    },
    // 用户共享操作
    async handelUserShare(row) {
      let params = {userId:row.userId}
      if (row.isShare == 1) {
        const {code} = await postUserDeleteShare(params);
        if(code === '1'){
          this.$message.success('操作成功');
          this.loadTable(false);
        }
      } else {
        const {code} = await postUserShare(params);
        if(code === '1'){
          this.$message.success('操作成功');
          this.loadTable(false);
        }
      }
    },
    checkUserShare() {
      this.shareTable.visible = true;
      this.getShareList();
    },
    add(rows){
      this.form.rule = FORM_ADMIN;
       this.$nextTick(()=>{
          this.form.fApi.updateRules({'roleIds':{options:[]}})
          this.form.fApi.updateRules({'roleIds':{options:this.userRoleOptions}})
      });
      if(rows === true){
        this.form.id = '';
        this.form.title="新增";
        this.$nextTick(()=>{
           this.form.fApi.disabled(false, 'loginName');
          this.form.fApi.disabled(false, 'password');
          this.form.fApi.updateValidate('password',[{required:true}], true)
          this.form.fApi.hidden(false,'password');
          this.form.fApi.setValue({
            loginName:'',
            status:1,
            userName:'',
            password:'',
            contact:'',
            roleIds:'',
            remark:''
          })
        })
      }else{
        this.form.id = rows.id;
        this.form.title="编辑";
        this.$nextTick(()=>{
          this.form.fApi.disabled(true, 'loginName');
          this.form.fApi.disabled(true, 'password');
          this.form.fApi.updateValidate('password',[{required:false}], true)
          this.form.fApi.hidden(true,'password');
          this.form.fApi.setValue({
            loginName:rows.loginName,
            status:rows.status,
            userName:rows.userName,
            contact:rows.contact,
            roleIds:rows.roleIds ? rows.roleIds.join(',') : '',
            remark:rows.remark
          })
        })
      }
      this.form.visible = true;
    },
    handleSubmit(){
      this.form.fApi.submit(async (formData, $f) => {
        try {
          let params = {};
            if(this.form.id){
              params.id = this.form.id;
            }else{
              params.password = md5(formData.password);
            }
            params.relationId = this.userInfo.relationId;
            params.status = formData.status;
            params.loginName = formData.loginName;
            params.userName = formData.userName;
            params.contact = formData.contact;
            params.roleIds = formData.roleIds.split(',');
            params.remark = formData.remark;
            const {code} = this.form.id ? await sysEditOperateUser(params) : await sysAddOperateUser(params);
            if(code === '1'){
              this.form.visible = false;
              this.loadTable(true);
            }
        } catch (error) {
          this.$message.info(JSON.stringify(error));
        }
      })
    },
    async del(row){
      const {code} = await sysOperateDelUser(row.id);
      if(code === '1'){
        this.$message.success('操作成功');
        this.loadTable(false);
      }
    },
    async resetPwd(row){
      let params = {id:row.id}
      const {code} = await sysResetPasswordOperateUser(params);
      if(code === '1'){
        this.$message.success('操作成功');
        this.loadTable(false);
      }
    },
   
    reset(){
      this.params.fApi.resetFields();
      this.loadTable(true);
    }
  }
}
</script>


